import { getDynamicProps } from "@/utils";
import { isProdMode } from "@/utils/env";
import { error } from "@/utils/log";
import { ValidateFieldsError } from "async-validator";
import { FormItemProp } from "element-plus/es";
import { nextTick, onUnmounted, ref, unref, watch } from "vue";
import {
  FormActionType,
  FormProps,
  FormSchema,
  UseFormReturnType,
} from "../types/form";
import { Nullable, Recordable } from "/#/global";
import { DynamicProps } from "/#/utils";

type Props = Partial<DynamicProps<FormProps>>;

export function useForm(props?: Props): UseFormReturnType {
  const formRef = ref<Nullable<FormActionType>>(null);
  const loadedRef = ref<Nullable<boolean>>(false);

  async function getForm() {
    const form = unref(formRef);
    if (!form) {
      error(
        "The form instance has not been obtained, please make sure that the form has been rendered when performing the form operation!"
      );
    }
    await nextTick();
    return form as FormActionType;
  }

  function register(instance: FormActionType) {
    isProdMode() &&
      onUnmounted(() => {
        formRef.value = null;
        loadedRef.value = null;
      });
    if (unref(loadedRef) && isProdMode() && instance === unref(formRef)) return;

    formRef.value = instance;
    loadedRef.value = true;

    watch(
      () => props,
      () => {
        props && instance.setProps(getDynamicProps(props));
      },
      {
        immediate: true,
        deep: true,
      }
    );
  }

  const methods: FormActionType = {
    // TODO promisify
    getFieldsValue: <T>() => {
      return unref(formRef)?.getFieldsValue() as T;
    },
    setProps: async (formProps: Partial<FormProps>) => {
      const form = await getForm();
      form.setProps(formProps);
    },
    setFieldsValue: async <T>(values: T) => {
      const form = await getForm();
      form.setFieldsValue<T>(values);
    },
    resetSchema: async (data: Partial<FormSchema> | Partial<FormSchema>[]) => {
      const form = await getForm();
      form.resetSchema(data);
    },
    validateField: async (
      props?: Array<FormItemProp>,
      callback?: (isValid: boolean, invalidFields?: ValidateFieldsError) => void
    ) => {
      const form = await getForm();
      form.validateField(props, callback);
    },

    resetFields: async () => {
      getForm().then(async (form) => {
        await form.resetFields();
      });
    },
    updateSchema: async function (
      data: Partial<FormSchema> | Partial<FormSchema>[]
    ): Promise<void> {
      const form = await getForm();
      form.updateSchema(data);
    },
    validate: async (
      callback?: (isValid: boolean, invalidFields?: ValidateFieldsError) => void
    ): Promise<any> => {
      const form = await getForm();
      return form.validate(callback);
    },
  };

  return [register, methods];
}
